package request;

import core.GameCharacter;
import java.io.OutputStream;

import response.ResponseBuddyAccept;
import core.GameUser;

/**
 * This class handles response received from user who was invited
 * to be someone's buddy.
 *
 * @author Zoran
 *
 * [ed this class handles request from client to accept a buddy's invite.]
 */
public class RequestBuddyAccept extends GameRequest{
    // User who accepts buddy-invite
    private GameUser invited;

    // User who sent buddy-invite
    private String inviterName;
    private GameUser inviter;
    // Accept invitation or not.
    private short accept;

    public void parse() {
        // Protocol: (String) characterName, (short)
        try {
            invited = client.getUser();
            inviterName = client.readString(dataIn);
            accept = client.readShort(dataIn);

            GameCharacter gc = gameServer.getGameDB().getCharacter(inviterName);
            if(gc != null) {
                inviter = new GameUser(gc.getUserID());
                gameServer.getGameDB().getUser(inviter.getID(), inviter);
            }

            // If buddy invitation accepted, add the character to list of user's buddies
            if(accept == 1) {
                gameServer.log("adding buddy with id: " + invited.getCharacter().getID() + "," + gc.getID(),"d");
                gameServer.getGameDB().addBuddy(invited.getCharacter().getID(),
                        gc.getID());
            }
        } catch(Exception e){
                gameServer.log("RequestBuddyAccept error: "+ inviterName,"e");
        }
    }

    @Override
    public void respond(OutputStream output) {
        ResponseBuddyAccept response = new ResponseBuddyAccept();
        if(inviter == null || !inviter.getOnline()) {
            response.setStatus((short)0);
        }

        response.setStatus((short)1);
        response.set(gameServer);
        response.setOut(output);
        response.run();
        // Need to update object user's queue with this response
        /* TODO implement
        gameServer.updateOneUserQueue(response, gameServer.getActiveUserList(), inviteeId);
         *
         */
    }
}